package com.android.project.games;

import java.util.ArrayList;
import java.util.List;

import javax.microedition.khronos.opengles.GL10;

import android.content.res.Configuration;
import android.opengl.GLSurfaceView;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;

import com.android.project.framework.Game;
import com.android.project.framework.Input.KeyEvent;
import com.android.project.framework.Input.TouchEvent;
import com.android.project.framework.gl.Camera2D;
import com.android.project.framework.gl.SpriteBatcher;
import com.android.project.framework.impl.GLGame;
import com.android.project.framework.impl.GLScreen;
import com.android.project.framework.impl.ViewGame;
import com.android.project.framework.math.OverlapTester;
import com.android.project.framework.math.Rectangle;
import com.android.project.framework.math.Vector2;
import com.android.project.games.World2.WorldListener;
import com.android.project.mysql.connection.AssociationWord;
import com.android.project.mysql.connection.ConnectionData;



public class GameScreen2 extends GLScreen {
	static final int GAME_READY = 0;
	static final int GAME_RUNNING = 1;
	static final int GAME_PAUSED = 2;
	static final int GAME_LEVEL_END = 3;
	static final int GAME_OVER = 4;
	int state;
	Camera2D guiCam;
	Vector2 touchPoint;
	SpriteBatcher batcher;
	
	ViewGame view;
	String stringa = "";
	World2 world2;
	WorldListener listener;
	WorldRenderer2 renderer;
	Vector2 position;
	List<TouchEvent> touchList;
	boolean keyboardShow = false;
	ConnectionData data;
	List<AssociationWord> listWord;
	Label newLabel;
	Rectangle pauseBounds;
	Rectangle quitBounds;
	Rectangle resumeBounds;
	List<KeyEvent> keyList;
	int prefixL;
	String check;
	InputMethodManager  m;
	Vibrator c;
	int result;
	//float render = 0;
	int lastScore;
	int over = 0;
	String level;
	int score;
	
	public GameScreen2(Game game) {
		super(game);
		// TODO Auto-generated constructor stub
		state = GAME_READY;
		guiCam = new Camera2D(glGraphics, 320, 480);
		touchPoint = new Vector2();
		position = new Vector2();
		batcher = new SpriteBatcher(glGraphics, 1000);
		view = glGraphics.getGlView();
		data = new ConnectionData();
		listener = (new WorldListener() {
			
			@Override
			public void wrong() {
				// TODO Auto-generated method stub
				Assets.playSound(Assets.wrongSound);
			}
			
			@Override
			public void right() {
				// TODO Auto-generated method stub
				Assets.playSound(Assets.rightSound);
				
			}
			
			@Override
			public void semi() {
				// TODO Auto-generated method stub
				Assets.playSound(Assets.semiSound);
			}
			
		
		});
				
		listWord = data.retrieveData("-1");
		m = (InputMethodManager) glGame.getApplicationContext().getSystemService("input_method");		 
		c = (Vibrator) glGame.getApplicationContext().getSystemService("vibrator");
		world2 = new World2(listener);	
		renderer = new WorldRenderer2(glGraphics, batcher, world2);
	    pauseBounds = new Rectangle(320- 32, 480- 32, 32, 32);
	    quitBounds = new Rectangle(160 - 150, 300 - 18, 300, 36);    
	    resumeBounds = new Rectangle(160 - 150, 300 - 40 , 300, 36);
	  
		score = 0;
		
	}

	@Override
	public void update(float deltaTime) {
		// TODO Auto-generated method stub
	
		switch(state){
		case GAME_READY:
			updateReady();
			break;
		case GAME_RUNNING:
			updateRunning(deltaTime);
			break;
		case GAME_PAUSED:
			updatePaused(deltaTime);
			break;
		case GAME_LEVEL_END:
			updateLevelEnd();
			break;
		case GAME_OVER:
			updateGameOver();
			break;
		}
		
	}

	private void updateReady() {
		// TODO Auto-generated method stub
		touchList = game.getInput().getTouchEvents();
		for (int i = 0; i < touchList.size(); i++){
			TouchEvent event = touchList.get(i);
			if(event.type == TouchEvent.TOUCH_UP )
				state = GAME_RUNNING;
				world2.state = World2.WORLD_STATE_READY;
			   

		}
		
		
	}

	private void updateRunning(float deltaTime) {
		
		// TODO Auto-generated method stub
	/*	if(over == 4){
			Settings.addScore(lastScore);
			Settings.save(game.getFileIO());
			state = GAME_LEVEL_END;	
			world2.state = World2.WORLD_STATE_LEVEL_END;
			m.hideSoftInputFromWindow(view.getWindowToken(), 0);
			//world2.keyboardShow = false;
			//world2.render = 0;
			over = 0;	
			//return;
			
		}*/
		
		String w = listWord.get(0).getWord();
		world2.generateLevel(w, deltaTime);
		//world2.update(deltaTime);
		touchList = game.getInput().getTouchEvents();
		keyList = game.getInput().getKeyEvents();
		
		if(world2.score != lastScore){
			lastScore = world2.score;
			score = lastScore;
		}
	//	world2.render = 3;
		
		//gestione del tasto indietro
		if(glGraphics.getGlView().isPressBack()){	
			/**world2.keyboardShow = false;
			world2.render = 0;*/
			world2.pressBack = true;
			glGraphics.getGlView().setPressBack(false);

		
		}
			
		for (int i = 0; i < touchList.size(); i++){
			TouchEvent event = touchList.get(i);
			touchPoint.set(event.x, event.y);
			guiCam.touchToWorld(touchPoint);
			if(event.type == TouchEvent.TOUCH_UP ){
				if(OverlapTester.pointInRectangle(pauseBounds, touchPoint)){
					Assets.playSound(Assets.clickSound);
					state = GAME_PAUSED;
					m.hideSoftInputFromWindow(view.getWindowToken(), 0);
					world2.state = World2.WORLD_STATE_GAME_PAUSED;
				//	world2.keyboardShow = false;
				//	world2.render = 0;
					
					//return;
				}
				else{
					c.vibrate(200);
				    m.showSoftInput(view, 0);
				   // world2.keyboardShow = true;
				  //  world2.render = 1;
				    world2.pressBack = false;
				    world2.state = World2.WORLD_STATE_RUNNING;
 
				}
			}
			
			
		}
		
		world2.update(deltaTime);
		if(world2.state == World2.WORLD_GAME_OVER){
			state = GAME_OVER;
			m.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
		else if(world2.state == World2.WORLD_STATE_LEVEL_END){
			Settings.addScore(lastScore);
			Settings.save(game.getFileIO());
			state = GAME_LEVEL_END;	
			m.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
		for(int i = 0; i < keyList.size(); i++){
			
			KeyEvent event = keyList.get(i);
		
			if(event.type == KeyEvent.KEY_UP){	
				
				if(event.keyCode == 67){
					
					if(stringa.length() > 0){
						prefixL = stringa.length() - 1;
						stringa = stringa.substring(0, prefixL);}
					else stringa = "";
					world2.enableLabel(stringa);
				}
				else if(event.keyCode == 66){
						//render = 2;
						over++;
						result = world2.checkWord(listWord);		
						Log.d("GameScreen2 result", "" + result);
						if(result == 0){
							stringa = "";
							listWord = data.retrieveData(listWord.get(1).getId());
							//return;
						}
						if(result == -1){ 			
							Message msg = new Message();
							msg.obj = "Hai sbagliato! Continua la catena da " + listWord.get(0).getWord();
							listWord = data.retrieveData(listWord.get(0).getId());
							((GLGame)game).getToastHandler().sendMessage(msg);
							stringa = "";
							//return;
	
						}
						else if(result > 0){
							Message msg = new Message();
							msg.obj = "Ti sei avvicinato! Continua la catena da qui!";
							((GLGame)game).getToastHandler().sendMessage(msg);
							listWord = data.retrieveData(listWord.get(result).getId());
							stringa = "";
							//return;
							
							
						}
						 
						
				}	
				else{		
					stringa = stringa.concat(String.valueOf(event.keyChar));	
					world2.enableLabel(stringa);	
					
				}	
				
			}

			 
		}
	
	}

	private void updatePaused(float deltaTime ) {
		// TODO Auto-generated method stub
		touchList = game.getInput().getTouchEvents();
		int len = touchList.size();
		world2.update(deltaTime);
		for(int i = 0; i < len; i++){
			TouchEvent event = touchList.get(i);
			if(event.type == TouchEvent.TOUCH_UP){
				touchPoint.set(event.x, event.y);
				guiCam.touchToWorld(touchPoint);
				if(OverlapTester.pointInRectangle(resumeBounds, touchPoint)){
					Assets.playSound(Assets.clickSound);
					state = GAME_RUNNING;
					return;
				}
				if(OverlapTester.pointInRectangle(quitBounds, touchPoint)){
					Assets.playSound(Assets.clickSound);
					game.setScreen(new MainMenuScreen(game));
					
					return;
				}	
			}
			
		}
		
		
	}

	private void updateLevelEnd() {
		// TODO Auto-generated method stub
		touchList = game.getInput().getTouchEvents();
		for(int i = 0; i < touchList.size(); i++){
			TouchEvent event = touchList.get(i);
			if(event.type == TouchEvent.TOUCH_UP){
				listWord = data.retrieveData("-1");	
				world2 = new World2(listener);
				renderer = new WorldRenderer2(glGraphics, batcher, world2);
				world2.score = lastScore;
				state = GAME_READY;
				return;
			}
					
		}
		
		
	}

	private void updateGameOver() {
		// TODO Auto-generated method stub
		touchList  = game.getInput().getTouchEvents();
		int len = touchList.size();
		for(int i = 0; i < len; i++) {
			TouchEvent event = touchList.get(i);
			if(event.type != TouchEvent.TOUCH_UP)
				continue;
			game.setScreen(new MainMenuScreen(game));
		}
		
	}

	@Override
	public void present(float deltaTime) {
		// TODO Auto-generated method stub
		GL10 gl = glGraphics.getGl();
		 gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
       
       
        gl.glEnable(GL10.GL_TEXTURE_2D);
        
        renderer.render(stringa);
        
        guiCam.setViewportAndMatrices();
		gl.glEnable(GL10.GL_BLEND);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		batcher.beginBatch(Assets.items);
		switch(state){
			case GAME_READY:
				presentReady();
				
				break;
			case GAME_RUNNING:
				presentRunning();
				break;
			case GAME_PAUSED:
				presentPaused();
				break;
			case GAME_LEVEL_END:
				presentLevelEnd();
				break;
			case GAME_OVER:
				presentGameOver();
				break;
				
		}
		batcher.endBatch();
		gl.glDisable(GL10.GL_BLEND);
		
	}
		
	

	

	private void presentGameOver() {
		// TODO Auto-generated method stub
		batcher.drawSprite(160, 300,236 ,50, Assets.gameOverRegion);
	}

	

	private void presentReady() {
		// TODO Auto-generated method stub
		//Assets.font.drawText(batcher, "Clicca sullo schermo per iniziare!", x , y);
		batcher.drawSprite(160, 240, 128, 50, Assets.clickRegion);
		
		
	}
	
	private void presentPaused() {
		// TODO Auto-generated method stub
		batcher.drawSprite(160, 300, 300, 36, Assets.quitRegion);
		batcher.drawSprite(160, 300 - 40, 300, 36, Assets.resumeRegion);
		
		
	}
	
	private void presentLevelEnd() {
		// TODO Auto-generated method stub
		
		batcher.drawSprite(160, 300, 290 ,160, Assets.levelEnd);
	}
	
	private void presentRunning() {
		// TODO Auto-generated method stub
		batcher.drawSprite(42, 480 - 16 , 79, 24, Assets.scoreRegion);
		Assets.font.drawText(batcher, " "  + String.valueOf(score),90, 480-16);
		batcher.drawSprite(320- 16, 480- 16, 32, 32, Assets.pauseRegion);
	
		
	}

	@Override
	public void pause() {
		// TODO Auto-generated method stub
		if(state == GAME_RUNNING)
			state = GAME_PAUSED;
		
	}

	@Override
	public void resume() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub
		
	}

}
